package com.yupi.longojcodesandbox.controller;

import com.yupi.longojcodesandbox.JavaNativeCodeSandbox;
import com.yupi.longojcodesandbox.model.ExecuteCodeRequest;
import com.yupi.longojcodesandbox.model.ExecuteCodeResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController("/")
public class MainController {

    //定义鉴权请求头和密钥
    private static final  String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @GetMapping("/health")
    public String healthCheck(){
        return "ok";
    }

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response){
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)){
        response.setStatus(403);
        return null;
        }
        if (executeCodeRequest==null){
            throw  new RuntimeException("请求参数为空");
        }
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.excuteCode(executeCodeRequest);
        return executeCodeResponse;
    }
}
